import React, { PureComponent } from 'react';
import { RouteComponentProps, withRouter } from 'react-router';
import Notification from '@/components/Notification';
import Toast from '@/components/Toast';
import UnSelectImg from '@/assets/images/video-unselect.png';
import SelectedImg from '@/assets/images/video-selected.png';
import VideoIcon from '@/assets/images/video-icon.png';
import VideoTips from '@/assets/images/video-tips.png';
// import { TXInfoOfType } from '@/store/models/card';
import { connect } from 'react-redux';
import RSAEncrypt from '@/common/rsa-encrypt';
import Service from './services';
import { videoText, isAndroidIos } from '@/common/utils';
import './index.less';
const isIOS = isAndroidIos();
interface VideoInfoProps extends RouteComponentProps {
  history: any;
  TXInfo: any;
  updateTXInfo: (payload: any) => Promise<any>;
}

interface VideoInfoState {
  selectSatus: boolean;
  preview: any;
  upStatus: any;
  fileData: any;
  desText: string;
}

class VideoUpload extends PureComponent<VideoInfoProps, VideoInfoState> {
  constructor(props: VideoInfoProps) {
    super(props);
    this.state = {
      selectSatus: false,
      preview: null,
      upStatus: false,
      fileData: null,
      desText: ''
    };
  }
  componentDidMount() {
    if (!this.props.TXInfo.phone) {
      this.props.history.replace(`/`);
      return;
    }
    let certNameEnc = RSAEncrypt.decrypt(this.props.TXInfo.certNameEnc);
    let desText = videoText(
      certNameEnc,
      new Date().getTime(),
      this.props.TXInfo.phone
    );

    this.setState({
      desText: desText
    });
  }
  //视频格式校验
  checkVideoType = (type: any) => {
    let typeArr = ['video/mp4', 'video/quicktime', 'video/mov'];
    let status = typeArr.includes(type);
    if (!status) {
      Toast.show('视频格式要求mp4、mov格式，请重新上传');
      return false;
    }
    return true;
  };
  //视频大小校验
  checkVideoSize = (size: any) => {
    let videoSize = size / 1024 / 1024;
    if (videoSize > 100) {
      Toast.show('视频大小超过了100M，请重新上传');
      return false;
    }
    return true;
  };
  //点击/取消 勾选
  slelctHandler = () => {
    this.setState({
      selectSatus: !this.state.selectSatus
    });
  };
  //input 上传文件触发的方法
  changePath = async (e: any) => {
    const file = e.target.files[0];
    if (
      !file ||
      !this.checkVideoType(file.type) ||
      !this.checkVideoSize(file.size)
    )
      return;
    let src = window.URL.createObjectURL(file);

    let preview = (
      <video
        id="videoRef"
        className="video-ref-content"
        src={src}
        autoPlay={isIOS}
      />
    );

    this.setState({ fileData: file, preview: preview, upStatus: true });
  };

  //上传接口
  upload = async () => {
    if (!this.state.fileData) return;
    const form = new FormData();
    form.append('file', this.state.fileData);
    form.append('phoneNum', RSAEncrypt.encrypt(this.props.TXInfo.phone));
    let result = (await Service.videoUpload(form)) || '';
    return result;
  };

  //提示用户勾选协议
  warnHandler = () => {
    if (this.state.selectSatus) return;
    Toast.show('请先勾选用户协议');
  };
  //点叉号 重新上传
  uploadAgain = () => {
    this.setState({
      upStatus: false,
      fileData: null
    });
  };
  //提交
  videoSumit = async () => {
    if (!this.state.selectSatus || !this.state.upStatus) {
      let errToast = !this.state.selectSatus
        ? '请先勾选用户协议'
        : '请上传视频';
      Toast.show(errToast);
      return;
    }
    let error = '上传中...';
    Notification.show(error, 600);
    let result = await this.upload();
    Notification.show('', 0.01);
    if (result) {
      this.props.history.replace(`/checkResult?type=3`);
    }
  };

  // 参数分别为改变之前的数据状态对象
  componentDidUpdate(prevProps: any, prevState: any) {
    if (!isIOS) return;
    if (prevState.upStatus !== this.state.upStatus) {
      let videoEle: any = document.getElementById('videoRef');
      if (videoEle) {
        videoEle.setAttribute('x5-playsinline', 'true');
        videoEle.setAttribute('playsinline', 'true');
        videoEle.setAttribute('webkit-playsinline', 'true');
        videoEle.addEventListener('timeupdate', () => {
          videoEle.pause();
          videoEle.currentTime = 0;
        });
      }
    }
  }

  render() {
    const { selectSatus, preview, upStatus, desText } = this.state;
    return (
      <div className="video-upload">
        <div className="video-upload-top">
          <div className="video-top-title">
            您需要在录入的视频中读出以下一段文字
          </div>
          <div className="video-top-content">
            <div className="video-top-content-text">{desText}</div>
          </div>
        </div>

        <div className="video-upload-content">
          <div className="video-content-top">
            <img
              className={`video-content-top-select ${
                selectSatus ? 'video-selected' : 'video-unselect'
              }`}
              src={selectSatus ? SelectedImg : UnSelectImg}
              onClick={this.slelctHandler}
              alt="icon"
            />
            <span className="video-content-text">
              同意京东采集您的视频信息，为了实名二次认证
            </span>
          </div>

          <div className="video-upload-main">
            {!upStatus && (
              <div className="video-upload-main-size">
                <div
                  className={`video-upload-left ${
                    selectSatus ? '' : 'opacity-show'
                  }`}
                >
                  {selectSatus && (
                    <input
                      className="video-upload-input"
                      type="file"
                      accept="video/*"
                      onChange={this.changePath}
                    />
                  )}
                  <img
                    onClick={this.warnHandler}
                    className="video-icon"
                    src={VideoIcon}
                    alt="icon"
                  />
                  <span className="video-icon-text">添加视频</span>
                </div>

                <div
                  className={`video-upload-right ${
                    selectSatus ? '' : 'opacity-show'
                  }`}
                >
                  <p className="video-upload-right-title">视频要求</p>
                  <p className="video-upload-right-des">
                    1.上传格式为<span className="video-text-red">MP4、MOV</span>
                    ，大小不超过
                    <span className="video-text-red">100M</span>，时长
                    <span className="video-text-red">30秒</span>以内。
                  </p>
                  <p className="video-upload-right-des">
                    2.保证光线充足，视频中录有完整人脸。
                  </p>
                </div>
              </div>
            )}

            {upStatus && (
              <div className="video-succ">
                <div className="video-media-poster">{preview}</div>
                <img
                  className="video-tips"
                  src={VideoTips}
                  alt="icon"
                  onClick={this.uploadAgain}
                />
                <div className="video-succ-bot">视频已添加</div>
              </div>
            )}
          </div>
        </div>

        <div className="video-footer">
          <div
            className={`video-footer-btn ${
              upStatus && selectSatus ? '' : 'grey'
            }`}
            onClick={this.videoSumit}
          >
            提交
          </div>
        </div>
      </div>
    );
  }
}

// @ts-ignore
const mapState = ({ CardReSold }) => ({
  TXInfo: CardReSold.TXInfo
});

// @ts-ignore
const mapDispath = ({ CardReSold }) => ({
  updateTXInfo: CardReSold.updateTXInfo
});

// @ts-ignore
export default connect(mapState, mapDispath)(withRouter(VideoUpload));
